package com.cl.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cl.blog.common.Const;
import com.cl.blog.common.Notice;
import com.cl.blog.entity.BAdmin;
import com.cl.blog.entity.BNotice;
import com.cl.blog.service.BAdminService;
import com.cl.blog.service.BNoticeService;
import com.cl.blog.mapper.BNoticeMapper;
import com.cl.blog.util.JwtUtil;
import com.cl.blog.vo.NoticeSearchVo;
import com.cl.blog.vo.NoticeVo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author object
 * @description 针对表【b_notice】的数据库操作Service实现
 * @createDate 2024-03-28 17:52:46
 */
@Service
public class BNoticeServiceImpl extends ServiceImpl<BNoticeMapper, BNotice>
		implements BNoticeService {
	@Autowired
	JwtUtil jwtUtil;
	@Autowired
	BAdminService bAdminService;

	@Override
	public boolean addNotice(NoticeVo notice, HttpServletRequest request) {

		String token = request.getHeader("token");
		Claims claim = jwtUtil.getClaimByToken(token, Const.GRADE_ADMIN);
		String adminId = claim.getSubject();

		String content = notice.getModel() + "：" + notice.getContent();

		BNotice bNotice = new BNotice();
		bNotice.setTitle(notice.getTitle());
		bNotice.setCreateTime(LocalDateTime.now());
		bNotice.setAdminId(Integer.valueOf(adminId));
		bNotice.setStatus(notice.getStatus());
		bNotice.setContent(content);

		boolean save = this.save(bNotice);
		return save;
	}

	@Override
	public List<BNotice> searchNotice(NoticeSearchVo noticeSearchVo) {
		BAdmin bAdmin = new BAdmin();
		if (!noticeSearchVo.getAdmin().isEmpty()) {
			bAdmin = bAdminService.getOne(new QueryWrapper<BAdmin>().eq("username", noticeSearchVo.getAdmin()));
			if (bAdmin == null) {
				bAdmin = new BAdmin();
			}
		}
		// 根据条件查
		List<BNotice> list = this.list(new QueryWrapper<BNotice>()
				.eq(bAdmin != null, "admin_id", bAdmin.getId())
				.eq(noticeSearchVo.getTitle() != null, "title", noticeSearchVo.getTitle())
				.eq(noticeSearchVo.getCreateTime() != null, "create_time", noticeSearchVo.getCreateTime())
		);

		for (BNotice bNotice : list) {
			BAdmin byId = bAdminService.getById(bNotice.getAdminId());
			bNotice.setAdmin(byId.getUsername());
		}

		return list;
	}
}




